<script lang="ts" setup>
    import { reactive, ref,defineExpose, onMounted, watch } from 'vue';
    import AddTableIntegrated from '../tableDetail/tableIntegrated/index.vue'
    import { PUSH_RATE } from '@/constants/dataManage'
    import ButtonGroup from '@/components/ButtonGroup/index'
    import MonacoEditor from '../monacoEditor/index.vue'
    import {BUILD_TABLE_BTN, TABLE_TYPE_GROUP, FieldList} from '@/constants/dataManage'
    import { Message } from '@arco-design/web-vue';
    import API from '@/services';
    // 新增字段
    const addFieldvisible = ref<boolean>(false)
    const showDdlTips = ref<boolean>(false)
        // 新增表结构
    const buildTable = ref<string>('buildTable')
    interface dataPushI {
        pushRate: number | string | undefined;
        tableName: string;
        tableDesc: string;
        fieldList: [],
        code: string
    }

    // 新建数据表参数
    const dataPushForm = reactive<dataPushI>({
        pushRate: undefined,
        tableName: '',
        tableDesc: '',
        fieldList: [],
        code: ''
    })
    const activeIndex = ref<number>(0)
    const activeTableIndex = ref<number>(0)

    const addTableRef = ref()
    // 引用 a-table 必须填写:model
    const formRef = ref();

    const visibleDrawer = () => {
        addFieldvisible.value = true
        // 以下是抽屉取消后，数据清空初始化
        activeIndex.value = 0
        activeTableIndex.value = 0
        dataPushForm.pushRate = undefined
        dataPushForm.tableName = ''
        dataPushForm.tableDesc = ''
        dataPushForm.fieldList =[]
        dataPushForm.code = ''
    }

    // 按钮样式选中状态
    const clickButton = (i: any) => {
        activeIndex.value = i
        showDdlTips.value = false
    }
    const clickTableTypeButton = (i: any) => {
        activeTableIndex.value = i
    }
    const emit = defineEmits(['addDataTable'])
    // 接受数据推送确定保存
    const handleOk = async () => {
        const err = await formRef.value.validate();
        let {pushRate, tableName, code, tableDesc} = dataPushForm
        let params :any = {
            dataBuldType: 2,
            pushRate,
            tableName,
            tableDesc,
            updateType: activeTableIndex.value + 1
        }
        if (activeIndex.value === 0) {
            const getChildTable = addTableRef.value.exposeFn()
            if (!getChildTable.data?.length) return;
            params.fieldList = FieldList(getChildTable)
            delete params.ddl
        } else {
            if (!code.trim()) {
                showDdlTips.value = true
                return
            }
            showDdlTips.value = false
            params.ddl = code
            delete params.fieldList
            delete params.tableName
        }
        if (!err) {
            try {
                const {code, data, msg} = await API.dataTable.postDataTableAddTable({
                    ...params
                })
                if (code === 200) {
                    addFieldvisible.value = false;
                    Message.success('添加数据表成功')
                    emit('addDataTable')
                }
            } catch (error) {}
        } else {
            throw new Error('校验错误')
        } 
    };
    watch(
        () => dataPushForm.code,
        (val) => {
            if (val) {
                showDdlTips.value = false
            }
        }
    )
    defineExpose({ visibleDrawer })
</script>
<template>
    <a-drawer 
        :visible="addFieldvisible" 
         @ok="handleOk"

        @cancel="() => {
            addFieldvisible = false;
        }" 
        :esc-to-close = "false"
        :mask-closable="false"
        placement="right"
        width="684px"
        title="接受数据推送"
        class="aDrawerPop"
        unmountOnClose>
        <a-form :model="dataPushForm" ref="formRef">
            <a-form-item field="pushRate" label="推送频率："
                :rules="[{required:true,message:'请选择推送频率'}]"
            >
                <a-select 
                    :style="{width:'320px'}" 
                    v-model="dataPushForm.pushRate" 
                    :options="PUSH_RATE"
                />
            </a-form-item>
            <a-alert>请首先在平台创建数据表，之后在源数据环境配置任务进行数据推送</a-alert>
            <a-form-item class="align-items" field="tableType">
                 <template #label>
                     <span class="col_red">*</span>
                     建表方式：
                 </template>
                <button-group @clickButton="clickButton" :buttonList="BUILD_TABLE_BTN" :init-active="activeIndex"></button-group>
            </a-form-item>
            <!-- 配置建表 -->
            <a-form-item v-if="activeIndex === 0" field="tableName" label="表名称：" 
                :rules="[{required:true,message:'请输入表名称'}]"
                :validate-trigger="['change','input']"
            >
                <a-input v-model="dataPushForm.tableName" :style="{width:'320px'}"/>
            </a-form-item>
             <!-- SQL建表方式 -->
            <a-form-item v-else class="ddl-edit" field="ddl" >   
                <template #label>
                    <span class="col_red">*</span>
                    建表DDL语句：
                </template>
                <template #extra>
                    <MonacoEditor v-model="dataPushForm.code" ></MonacoEditor>
                </template>
                
            </a-form-item>
            <div v-show="showDdlTips" class="ddl-tips ml-90 col_red">
                请输入DDL语句
            </div>
            <a-form-item field="tableDesc" label="表描述：" :style="{marginBottom:'10px'}">
                <a-textarea v-model="dataPushForm.tableDesc" :style="{width: '424px'}"/>
            </a-form-item>
           
            <a-form-item class="align-items" field="tableType">
                <template #label>
                    <span class="col_red">*</span>
                    表类型：
                </template>
               <button-group @clickButton="clickTableTypeButton" :buttonList="TABLE_TYPE_GROUP"></button-group>
            </a-form-item>
            <a-form-item class="extra-add-feild" v-show="activeIndex === 0" >
                <template #label>
                    <span class="col_red">*</span>
                    表结构：
                </template>
                <template #extra>
                    <add-table-integrated ref="addTableRef" :updateTable="buildTable"></add-table-integrated>
                </template>
            </a-form-item>
            
        </a-form>
    </a-drawer>

</template>
<style>
.aDrawerPop {
    z-index: 1001 !important;
}
</style>
<style lang="scss" scoped>
    .table-top {
        display: flex;
        justify-content: space-between;
    }
    .table-title {
        display: flex;
    }
    .align-items {
        align-items: center;
    }
    .extra-add-feild :deep(.arco-form-item-extra) {
        position: relative;
        width: 100%;
        height: 100%;
    }

    .ddl-edit :deep(.arco-form-item-extra) {
        margin-left: -112px;
    }
    .ddl-tips {
        margin-top: -16px;
        padding-bottom: 10px;
    }
    

</style>